var $ = window.$;
var jade = require('jade');
var animate = require('../../../util/animate');
var event = require('../../../core/event');
var util = require('../../../util/index');
var uiUtil = require('../../../util/ui');
var config = require('../../../core/config');
var slide = require('../../../core/slide');

var _inited = false;

/**
 * grid设定
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		this.slideId = [];
		event.bind(event.events.key.up, 'grid_aux', this);
		event.lock('key', 'grid_aux');
		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}
	},

	add: function () {
		var pos = this.parent.find("#dialog_grid_pos").val();
		pos = parseFloat(pos);
		pos = util.clamp(pos, 0, 100);

		var info = this.manager.getEditInfo();
		if(!info.grid){
			info.grid = {};
		}
		if(!info.grid.referVert){
			info.grid.referVert = [];
		}
		info.grid.referVert.push(pos);
		event.trigger(event.events.note.change);
		event.trigger(event.events.grid.change);
	},

	show: function(param){
		//参数准备, param外部已检验
		this.param = param;
		var mode = param.meta.mode;
		if(mode != 3){
			return;
		}
		var tmpl = jade.compileFile('./tmpl/grid/gridaux.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_grid_aux');
		this.parent.on('click','.g_barhead i', function () {
			self.hide();
		});
		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'close'){
				self.add();
				self.hide();
			}else if(type == 'clear'){
				util.setJsonChainValue(self.param, 'extra.grid.referVert', []);
				event.trigger(event.events.note.change);
				event.trigger(event.events.grid.change);
			}
		});

		var sliders = this.parent.find('.g_slide');
		var inputs = this.parent.find('input');

		var id = slide.on({
			parent: sliders.eq(0),
			min: 1,
			max: 100,
			onchange: function(val){
				inputs.eq(0).val(Math.round(val));
			}
		});
		this.slideId.push(id);

		inputs.keyup(function (e) {
			var target = $(this);
			var id = target.attr('id');
			if(id == 'dialog_grid_pos'){
				slide.setVal(self.slideId[0], parseInt(target.val()));
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent);
		event.trigger(event.events.global.blur);

	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'grid_aux');
			for(var i=0;i<self.slideId.length;i++){
				slide.off(self.slideId[i]);
			}
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;